package com.cskaoyan.market.service.impl;

import com.cskaoyan.market.db.domain.*;
import com.cskaoyan.market.db.mapper.MarketOrderGoodsMapper;
import com.cskaoyan.market.db.mapper.MarketOrderMapper;
import com.cskaoyan.market.db.mapper.MarketUserMapper;
import com.cskaoyan.market.service.MarketOrderService;
import com.cskaoyan.market.util.MyBatisUtil;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.session.SqlSession;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MarketOrderServiceImpl implements MarketOrderService {

    @Override
    public List<MarketOrder> readOrderList(String page, String limit, String sort, String order, String orderId, String userId, String orderSn, String[] timeArrays, String[] orderStatusArrays) {
        SqlSession session = MyBatisUtil.getSession();
        MarketOrderMapper mapper = session.getMapper(MarketOrderMapper.class);
        MarketOrderExample marketOrderExample = new MarketOrderExample();
        marketOrderExample.orderBy(sort + " " + order);
        MarketOrderExample.Criteria criteria = marketOrderExample.or().andDeletedEqualTo(false);
        if (userId != null && !"".equals(userId)) {
            System.out.println("userid");
            criteria.andUserIdEqualTo(Integer.parseInt(userId));
        }
        if (orderSn != null && !"".equals(orderSn)) {
            System.out.println("orderSn");
            criteria.andOrderSnEqualTo(orderSn);
        }

        if (timeArrays != null && timeArrays[0]!=null && timeArrays[1]!=null) {
            System.out.println("timeArrays[0]"+timeArrays[0]);
            System.out.println("timeArrays[1]"+timeArrays[1]);
            criteria.andAddTimeGreaterThan(LocalDateTime.parse(timeArrays[0], DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            criteria.andAddTimeLessThan(LocalDateTime.parse(timeArrays[1], DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }
        if (orderStatusArrays != null && orderStatusArrays.length > 0) {
            System.out.println("orderStatusArrays");
            criteria.andOrderStatusIn(packageStrings(orderStatusArrays));
        }
        PageHelper.startPage(Integer.parseInt(page), Integer.parseInt(limit));
        List<MarketOrder> marketOrders = mapper.selectByExample(marketOrderExample);

        session.commit();
        session.close();
        return marketOrders;
    }

    @Override
    public Map<String, Object> readOrderDetail(String id) {
        SqlSession session = MyBatisUtil.getSession();
        MarketOrderMapper mapper = session.getMapper(MarketOrderMapper.class);
        MarketOrderExample marketOrderExample = new MarketOrderExample();
        marketOrderExample.or().andDeletedEqualTo(false).andIdEqualTo(Integer.parseInt(id));
        MarketOrder marketOrder = mapper.selectOneByExample(marketOrderExample);
        HashMap<String, Object> orders = new HashMap<>();
        session.commit();
//        session.close();
        if (marketOrder==null){
            session.close();
            return orders;
        }
        System.out.println(marketOrder);
        System.out.println("here");
        orders.put("order",marketOrder);
        MarketOrderGoodsMapper orderGoodsMapper = session.getMapper(MarketOrderGoodsMapper.class);
        MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        marketOrderGoodsExample.or().andOrderIdEqualTo(marketOrder.getId()).andDeletedEqualTo(false);
        List<MarketOrderGoods> marketOrderGoods = orderGoodsMapper.selectByExample(marketOrderGoodsExample);
        session.commit();
//        session.close();
        System.out.println("marketOrderGoods ok");
        if (marketOrderGoods.size()==0){
            System.out.println("marketOrderGoods.size()==0");
            session.close();
            return orders;
        }
        System.out.println("herererer");
        orders.put("orderGoods",marketOrderGoods);
        MarketUserMapper UserMapper = session.getMapper(MarketUserMapper.class);
        System.out.println(marketOrder.getUserId());
        MarketUser marketUser = UserMapper.selectByPrimaryKeySelective(marketOrder.getUserId(),MarketUser.Column.nickname,MarketUser.Column.avatar);
        if (marketUser==null){
            System.out.println("marketUser");
            session.commit();
            session.close();
            return orders;
        }
        System.out.println(marketUser);
        orders.put("user",marketUser);
        session.commit();
        session.close();
        return orders;
    }

    @Override
    public String getChannel() {
        return "{\"errno\":0,\"data\":[{\"code\":\"ZTO\",\"name\":\"中通快递\"},{\"code\":\"YTO\",\"name\":\"圆通速递\"},{\"code\":\"YD\",\"name\":\"韵达速递\"},{\"code\":\"YZPY\",\"name\":\"邮政快递包裹\"},{\"code\":\"EMS\",\"name\":\"EMS\"},{\"code\":\"DBL\",\"name\":\"德邦快递\"},{\"code\":\"FAST\",\"name\":\"快捷快递\"},{\"code\":\"ZJS\",\"name\":\"宅急送\"},{\"code\":\"TNT\",\"name\":\"TNT快递\"},{\"code\":\"UPS\",\"name\":\"UPS\"},{\"code\":\"DHL\",\"name\":\"DHL\"},{\"code\":\"FEDEX\",\"name\":\"FEDEX联邦(国内件)\"},{\"code\":\"FEDEX_GJ\",\"name\":\"FEDEX联邦(国际件)\"}],\"errmsg\":\"成功\"}";
    }

//101: '未付款', 102: '用户取消', 103: '系统取消',
// 201: '已付款', 202: '申请退款', 203: '已退款',
// 301: '已发货', 401: '用户收货', 402: '系统收货'
    @Override
    public int ShipOrder(String orderId, String shipChannel, String shipSn) {
        SqlSession session = MyBatisUtil.getSession();
        MarketOrderMapper mapper = session.getMapper(MarketOrderMapper.class);
        MarketOrderExample marketOrderExample = new MarketOrderExample();
        MarketOrderExample.Criteria or = marketOrderExample.or();
        or.andIdEqualTo(Integer.parseInt(orderId));
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setShipChannel(shipChannel);
        marketOrder.setShipSn(shipSn);
        marketOrder.setOrderStatus(Short.parseShort("301"));
        marketOrder.setShipTime(LocalDateTime.now());
        marketOrder.setUpdateTime(LocalDateTime.now());
        System.out.println("ship3");
        int i = mapper.updateByExampleSelective(marketOrder, marketOrderExample);
        System.out.println("ship over");
        session.commit();
        session.close();
        return i;
    }

    @Override
    public int refundOrder(String orderId) {
        SqlSession session = MyBatisUtil.getSession();
        MarketOrderMapper mapper = session.getMapper(MarketOrderMapper.class);
        MarketOrderExample marketOrderExample = new MarketOrderExample();
        MarketOrderExample.Criteria or = marketOrderExample.or();
        or.andIdEqualTo(Integer.parseInt(orderId));
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setOrderStatus(Short.parseShort("203"));
        marketOrder.setUpdateTime(LocalDateTime.now());
        int i = mapper.updateByExampleSelective(marketOrder, marketOrderExample);
        session.commit();
        session.close();
        return i;
    }

    @Override
    public int deleteOrder(String orderId) {
        SqlSession session = MyBatisUtil.getSession();
        MarketOrderMapper mapper = session.getMapper(MarketOrderMapper.class);
        MarketOrderExample marketOrderExample = new MarketOrderExample();
        MarketOrderExample.Criteria or = marketOrderExample.or();
        or.andIdEqualTo(Integer.parseInt(orderId));
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setDeleted(true);
        marketOrder.setUpdateTime(LocalDateTime.now());
        int i = mapper.updateByExampleSelective(marketOrder, marketOrderExample);
        session.commit();
        session.close();
        return i;
    }

    @Override
    public List<MarketOrder> list(int page, int limit, String sort, String order, LocalDateTime start, LocalDateTime end, int userId, int orderId, String orderSn, ArrayList<Short> orderStatus) {
        SqlSession session = MyBatisUtil.getSession();
        MarketOrderMapper mapper = session.getMapper(MarketOrderMapper.class);
        MarketOrderExample marketOrderExample = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = marketOrderExample.or();
//排除逻辑删除
        criteria.andDeletedEqualTo(false);
//如果起始时间不为null，则在其中进行选择
        if (start != null && end != null) {
            criteria.andAddTimeBetween(start, end);
        }
//用户id
        if (userId != 0) {
            criteria.andUserIdEqualTo(userId);
        }
//订单id
        if (orderId != 0) {
            criteria.andIdEqualTo(orderId);
        }
//订单编号
        if (orderSn != null && !"".equals(orderSn)) {
            criteria.andOrderSnEqualTo(orderSn);
        }
//订单状态
        if (orderStatus != null && orderStatus.size() > 0) {
            criteria.andOrderStatusIn(orderStatus);
        }
//排序分页
        marketOrderExample.setOrderByClause(sort + " " + order);
        PageHelper.startPage(page, limit);

        List<MarketOrder> marketOrders = mapper.selectByExample(marketOrderExample);

        return marketOrders;
    }

    private List<Short> packageStrings(String[] orderStatusArrays) {
        List<Short> shorts = new ArrayList<>();
        for (String orderStatusArray : orderStatusArrays) {
            shorts.add(Short.parseShort(orderStatusArray));
        }
        return shorts;
    }
}
